<?php
  class EmailCentralDirectComponent extends CComponent
  {
  	public $db;
  	function init(){
		
  	}
  	
  	public function sendByTemplate($tpl_id,$email,$args=array(),$cc=null,$bcc=null)
  	{
		$connection = new CDbConnection($this->db['connectionString'],$this->db['username'],$this->db['password']);
		
		$sql = "SELECT * FROM template where id = :id";
		$command=$connection->createCommand($sql);
		$emailTemplate = $command->queryRow(true,array(
			':id'	=> $tpl_id,
		));
		if(!$emailTemplate){
			throw new Exception('Template not found',404);	
		}
		
		$emailValidator = new CEmailValidator();
		if (!$emailValidator->validateValue($email))
			throw new CHttpException(460, Yii::t('message', 'Invalid email', array(':email'=>$email)));
		$subject = $emailTemplate['subject'];
		$content = $emailTemplate['template'];
		
		if(!is_array($args)){
			if(strpos($args,'|=|') !== false){
				$array_args = preg_split("(\|=\||\|;\|)",$args);
			}
			else{
				$array_args = preg_split("(=|;)",$args);
			}

			$args = array();
			if(count($array_args)%2 != 0) throw new CHttpException(462, Yii::t('message', 'args error!'));
			for($i = 0 ; $i < count($array_args); $i++){
				if($i%2 == 0 && $i < count($array_args)){
					$args[$array_args[$i]] =$array_args[$i+1];
				}
			}
		}

		foreach($args as $key => $value){
			$subject = str_replace('$'.$key,$value,$subject);
			$content = str_replace('$'.$key,$value,$content);
		}

		$sql="INSERT INTO outbox (template_id, `to`,subject,content,cc,bcc) VALUES(:template_id,:to,:subject,:content,:cc,:bcc)";
		$command=$connection->createCommand($sql);
		$command->execute(array(
			':template_id'	=> $tpl_id,
			':to'	=> $email,
			':subject'	=> $subject,
			':content'	=> $content,
			':cc'	=> $cc,
			':bcc'	=> $bcc,
		));
		return true;
  	}
  }
?>
